package pikasial.images;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import pikasial.utils.ExtensionsImages;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifDirectory;

public class EXIFData {

	protected ExifDirectory exifDir;
	protected Metadata meta;
	private HashMap<String,String> exifData;
	private Date datePrise;
	private int imageHeight;
	private int imageWidth;

	@SuppressWarnings("unchecked")
	public EXIFData(PikImage pik) throws IncompatibleImageFormatException, JpegProcessingException, MetadataException {
		if (pik.getType() != ExtensionsImages.JPEG && pik.getType() != ExtensionsImages.JPG)
			throw new IncompatibleImageFormatException();
		exifData = new HashMap<String,String>();
		meta = JpegMetadataReader.readMetadata(pik.getJavaFile());
		Iterator iter = meta.getDirectoryIterator();
		while (iter.hasNext()) {
			Directory dir = (Directory) iter.next();
			if (dir instanceof ExifDirectory) {
				exifDir = (ExifDirectory) dir;
				Iterator tags = dir.getTagIterator();
				while (tags.hasNext()) {
					Tag t = (Tag) tags.next();
					if (!t.getTagName().toLowerCase().contains("unknown"))
						exifData.put(t.getTagName(),t.getDescription());
					if (t.getTagType() == ExifDirectory.TAG_DATETIME) {
						datePrise = dir.getDate(t.getTagType());
					} else if (t.getTagType() == ExifDirectory.TAG_EXIF_IMAGE_HEIGHT) {
						imageHeight = dir.getInt(t.getTagType());
					} else if (t.getTagType() == ExifDirectory.TAG_EXIF_IMAGE_WIDTH) {
						imageWidth = dir.getInt(t.getTagType());
					}
				}
			}
		}
	}

	public Set<String> getTagNameSet() { return exifData.keySet(); }

	public String getDescription(String tagName) {
		return exifData.get(tagName);
	}

	public boolean containsTag(String tagName) {
		return exifData.containsKey(tagName);
	}

	public Date getDatePrise() {
		return datePrise;
	}

	public int getImageWidth() {
		return imageWidth;
	}

	public int getImageHeight() {
		return imageHeight;
	}
}
